<?php
/**
* @file $Id: upgrade.php 437 2007-04-23 00:57:51Z focus-sis $
* @package Focus/SIS
* @copyright Copyright (C) 2006 Andrew Schmadeke. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
* Focus/SIS is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/

session_start();
if(!$_SESSION['USERNAME'])
	$_SESSION['USERNAME'] = 'upgrade';
$_FOCUS['User'] = array('PROFILE'=>'admin');
require_once('Warehouse.php');
ini_set('max_execution_time',0);
//error_reporting(0);
Warehouse('header');


echo '<BODY background=assets/bg.gif>';
echo DrawPNG('themes/'.Preferences('THEME').'/logo.png','border=0 width=154 height=34');
DrawHeader('Focus/SIS Upgrade');

if($_REQUEST['current_version'] && $handle = opendir($staticpath."UPGRADES/"))
{
	echo '<BR><BR>';
	PopTable('header',_('Upgrade Progress'));
	echo '<CENTER><TABLE cellpadding=0 cellspacing=0 style="border: inset #C9C9C9 2px;"><TR><TD><TABLE height=19 cellspacing=0 border=0 bgcolor=#FFFFFF><TR>';
	for($i=1;$i<=100;$i++)
		echo '<TD id=cell'.$i.' width=3 bgcolor=#FFFFFF></TD>';
	echo '</TR></TABLE></TD></TR></TABLE><BR><DIV id=percentDIV><IMG SRC=assets/spinning.gif> '._('Processing').' ... </DIV></CENTER>';
	PopTable('footer');
	ob_flush();
	flush();
	ini_set('MAX_EXECUTION_TIME',0);

	if(!is_array($IgnoreFiles))
		$IgnoreFiles=Array();
	
	while(false !== ($file = readdir($handle)))
	{
		if(strpos($file,'.php')!==false || $file=='Centre' || $file == "." || $file == ".." || in_array($file,$IgnoreFiles))
			continue;

		if($file==$_REQUEST['current_version'])
			$go = true;		
		
		if($go)
		{
			$sql_array = array();
			// TAKEN FROM OSCOMMERCE INSTALL
			$FP = fopen($staticpath.'/UPGRADES/'.$file,'rb');
			$restore_query = fread($FP,filesize($staticpath.'/UPGRADES/'.$file));
			$restore_query = str_replace("\r","\n",$restore_query);
			fclose($FP);
			
			$sql_array = array();
			$sql_length = strlen($restore_query);
			$pos = strpos($restore_query, ';');
			for($i=$pos; $i<$sql_length; $i++)
			{
				if($restore_query[0] == '-' && $restore_query[1] == '-')
				{
					$restore_query = ltrim(substr($restore_query, strpos($restore_query, "\n")));
					$sql_length = strlen($restore_query);
					$i = strpos($restore_query, ';')-1;
					continue;
				}
				if($restore_query[($i+1)] == "\n")
				{
					for($j=($i+2); $j<$sql_length; $j++)
					{
						if(trim($restore_query[$j]) != '')
						{
							$next = substr($restore_query, $j, 6);
							if($next[0] == '-' && $next[1] == '-')
							{
								// find out where the break position is so we can remove this line (#comment line)
								for($k=$j; $k<$sql_length; $k++)
								{
									if($restore_query[$k] == "\n")
										break;
								}
								$query = substr($restore_query,0,$i+1);
								$restore_query = substr($restore_query, $k);
								// join the query before the comment appeared, with the rest of the dump
								$restore_query = $query . $restore_query;
								$sql_length = strlen($restore_query);
								$i = strpos($restore_query, ';')-1;
								continue 2;
							}
							break;
						}
				  }
					if($next == '')
					{// get the last insert query
					$next = 'insert';
					}
				  if((eregi('create', $next)) || (eregi('insert', $next)) || (eregi('drop', $next) || (eregi('update', $next) || (eregi('alter', $next) || (eregi('delete', $next))))) )
				  {
					$next = '';
					$sql_array[] = substr($restore_query, 0, $i);
					$restore_query = ltrim(substr($restore_query, $i+1));
					$sql_length = strlen($restore_query);
					$i = strpos($restore_query, ';')-1;
				  }
				}
			}
			for ($i=0; $i<sizeof($sql_array); $i++)
			{
				DBQuery($sql_array[$i]);
			}
			if(file_exists($staticpath.'/UPGRADES/'.str_replace('.sql','.php',$file)))
				include($staticpath.'/UPGRADES/'.str_replace('.sql','.php',$file));			
		}
	}
	// END OSCOMMERCE SECTION
	
	echo '<script language="javascript">'."\r";
	echo 'addHTML("<IMG SRC=assets/spinning.gif> '._('Optimizing').' ... ","percentDIV",true);'."\r";
	echo '</script>';
	echo str_pad(' ',4096);
	ob_flush();
	flush();
	
	DBQuery("VACUUM");
	DBQuery("ANALYZE");
	
	echo '<script language="javascript">'."\r";
	echo 'addHTML("<IMG SRC=assets/check.gif width=15> <B>'._('Done').'... <A HREF=index.php>Continue</A></B>","percentDIV",true);'."\r";
	echo '</script>';
	ob_end_flush();
}
else
{
	// Load upgrade files.
	if($handle = opendir($staticpath."UPGRADES/")) 
	{
		if(!is_array($IgnoreFiles))
			$IgnoreFiles=Array();
	
		while (false !== ($file = readdir($handle))) 
		{				
			// if filename isn't '.' '..' or in the Ignore list... load it.
			if($file != "." && $file != ".." && $file!='Centre' && !in_array($file,$IgnoreFiles) && strpos($file,'.php')===false)
				$str .= '<INPUT type=radio name=current_version value="'.$file.'">'.str_replace('Focusv','Focus/SIS v',substr($file,0,strpos($file,'-'))).'<BR>';
		}

		$str .= '<BR><INPUT type=submit value=Upgrade>';
		echo '<BR><BR>';
		echo '<FORM action=upgrade.php method=POST>';
		DrawBlock('Select the current version of your Focus/SIS installation',$str);
		echo '</FORM>';
	}


}

if($_SESSION['USERNAME']=='upgrade')
	unset($_SESSION['USERNAME']);

Warehouse('footer');
?>